package com.datn.utils.places;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;


public class Json_Place extends Activity
{

	private static final String TAG = Json_Place.class.getName();
	private static final String MAP_API_URL = "http://maps.google.com/maps";
	private static final String EXPORT_TYPE = "json";
	private static final String UTF_8 = "utf-8";
	private static final int NUM_OF_PLACE = 10;
	
	private static final double DEGREES_TO_RADIANS = (double)(180/Math.PI);
	//earth’s radius (mean radius = 6367.45 km)
	private final static double EARTHS_RADIUS = 6378100; // metre
	
	private Context mContext;
	private SharedPreferences mPrefs;
	private Place place;
	//private Place nearbyPlace = null;
	public Json_Place(Context context) 
	{
		// TODO Auto-generated constructor stub
		this.mContext = context;
		this.mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
	}
	
 	
//---------------------------------------------------------------------------------	
public List<Place> getListAdressByType(String place,GeoPoint GPS) throws Exception
{
			if (place == null) {
				Log.e(TAG, "Place is null");
				throw new IllegalArgumentException();
			}
			
			List<Place> result = null;
	/* http://maps.google.com/maps?q=atm&sll=21.029505,105.850566&num=10&output=json */

			try {
				URL mapUri = new URL(MAP_API_URL +
						"?q=" + place + 
						"&sll=" 
						+ GPS.getLatitudeE6()/1E6 
						+ "," 
						+GPS.getLongitudeE6()/1E6
						+  
						"&num=" + NUM_OF_PLACE +
						"&output=" + EXPORT_TYPE +"&hl="+"vi"+
						"&oe=" + UTF_8);
				String jsonResponse = getResponseFromUrl(mapUri);
				if (jsonResponse != null) 
				{
					if (jsonResponse.contains("while(1);")) 
					{
						jsonResponse = jsonResponse.replace("while(1);", "");
					}
					
					// Create new JsonObject
					JSONObject jsonObject = new JSONObject(jsonResponse);
					String marker = jsonObject.getString("overlays");
					marker = marker.replace("{\"markers\":", "");
					marker = urlDecode(marker);
				
					// Extract json response to place
					result = jsonToListAddress(marker);
				} else 
				{
					Toast.makeText(mContext, "Không tìm thấy ", Toast.LENGTH_LONG).show();
				}
			} catch (MalformedURLException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
}
//------------------------------------------------
private List<Place> jsonToListAddress(String str_places) 
{
	try {
		List<Place> places = new ArrayList<Place>();
		JSONArray  jsonPlaces  = new JSONArray(str_places);
		for (int i = 0; i < jsonPlaces.length(); i ++) 
		{
			JSONObject jsonPlace = (JSONObject)jsonPlaces.get(i);	
			JSONObject jsonLatLng = new JSONObject(jsonPlace.getString("latlng"));
			Place place   = new Place();
			place.setAddressLine(jsonPlace.getString("laddr"));
			place.setName(jsonPlace.getString("name"));
			place.setLatitude(jsonLatLng.getDouble("lat"));
			place.setLongtitude(jsonLatLng.getDouble("lng"));
			places.add(place);
		}
		return places;
	} catch (JSONException e) 
	{
		// TODO: handle exception
		e.printStackTrace();
	}
	return null;
}
//-----------------------------------
private static String getResponseFromUrl(URL url) 
{
	try {
		URLConnection urlConnection = url.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
		StringBuilder strBuilder = new StringBuilder();
		String temp;
		while ((temp = in.readLine()) != null) {
			strBuilder.append(temp);
		}
		return strBuilder.toString();
	} catch (IOException e) {
		// TODO: handle exception
		e.printStackTrace();
	} 
	return null;
}
//--------------------------------------
private static String urlDecode(String target) 
{
	try {
		return URLDecoder.decode(target, "utf-8");
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	return null;
}
//***********************************************************************
//-----------------------------------------------------------------------	

public void setNearbyPlace(Place p) 
{
	// TODO Auto-generated method stub
	SharedPreferences.Editor editor = mPrefs.edit();
	editor.putString("PLACE_NAME", p.getName());
	editor.putString("ADDRESS_LINE", p.getAddressLine());
	editor.putString("LATITUDE", String.valueOf(p.getLatitude()));
	editor.putString("LONGTITUDE", String.valueOf(p.getLongtitude()));
	editor.commit();
}


public Place getNearbyPlace()
{
	place = new Place();
	place.setName(mPrefs.getString("PLACE_NAME", "unknown location"));
	place.setAddressLine(mPrefs.getString("ADDRESS_LINE", "unknown location"));
	place.setLatitude(Double.parseDouble(mPrefs.getString("LATITUDE", "0.0")));
	place.setLongtitude(Double.parseDouble(mPrefs.getString("LONGTITUDE", "0.0")));
	return place;
}

public void clearPreferences()
{
	SharedPreferences.Editor editor =mPrefs.edit();
	editor.clear().commit();
}

//***********************************************************************/


private static double calclateArc(double aLat, double aLong, double bLat, double bLong) {
	double aLatRad  = aLat / DEGREES_TO_RADIANS;
    double aLongRad = aLong / DEGREES_TO_RADIANS;
    double bLatRad  = bLat / DEGREES_TO_RADIANS;
    double bLongRad = bLong / DEGREES_TO_RADIANS;

    // Calculate the length of the arc that subtends point a and b
    double t1 = Math.cos(aLatRad)*Math.cos(aLongRad)*Math.cos(bLatRad)*Math.cos(bLongRad);
    double t2 = Math.cos(aLatRad)*Math.sin(aLongRad)*Math.cos(bLatRad)*Math.sin(bLongRad);
    double t3 = Math.sin(aLatRad)*Math.sin(bLatRad);
    double tt = Math.acos(t1 + t2 + t3);
    return tt;
}


public static double calculateDistance(Place from, GeoPoint to) {
	return calclateArc(from.getLatitude(), from.getLongtitude(), 
			to.getLatitudeE6()/1E6, to.getLongitudeE6()/1E6)* EARTHS_RADIUS;
}
//-----------------------------------------------------------------------
}
